<?php

namespace app\api\controller\product;

use AlibabaCloud\Tea\Request;
use app\api\model\plus\seckill\Product as SeckillProductModel;
use app\api\model\product\Product as ProductModel;
use app\api\model\order\Cart as CartModel;
use app\api\controller\Controller;
use app\api\model\settings\Setting as SettingModel;
use app\api\model\shop\FullReduce as FullReduceModel;
use app\api\model\user\Visit as VisitModel;
use app\api\service\common\RecommendService;
use app\common\library\helper;
use app\common\service\qrcode\ProductService;
use app\api\model\user\Favorite as FavoriteModel;
use app\api\model\plus\coupon\Coupon as CouponModel;
use app\common\model\supplier\Service as ServiceModel;
use app\common\model\stall\Product as StallProductModel;
use think\facade\Cache;

/**
 * 商品控制器
 */
class Product extends Controller
{
    /**
     * 商品列表
     */
    public function lists()
    {
        // 整理请求的参数
        $param = array_merge($this->postData(), [
            'product_status' => 10,
            'audit_status' => 10,
            'is_show' => 1,    //显示可搜索
        ]);
        // 获取列表数据
        $model = new ProductModel;
        $list = $model->getList($param, $this->getUser(false));
        return $this->renderSuccess('', compact('list'));
    }


    public function getSearchKeywords(){
        $user = $this->getUser(false);
        $keywords = $this->getData('keywords');
        $keywords = preg_replace('/\s/', '',$keywords);
        $model = new ProductModel;
        $list = [];
        if($keywords){
            $model = $model->where('search', 'like', '%' .$keywords. '%');
            $model = $model->where('is_delete', '=', 0);
            $model = $model->where('is_show', '=', 1);
            $model = $model->where('audit_status', '=', 10);
            $model = $model->where('product_status', '=', 10);
            $supplier_id = Cache::get($user['user_id'] . '_supplier_id');
            if ($supplier_id != null) {
                $model = $model->whereIn('shop_supplier_id', $supplier_id);
            }
            //搜索禁止查询出秒杀的商品
            $seckill_product_ids = (new SeckillProductModel())->getSeckillAtivityProduct(); //秒杀商品id
            $model = $model->where('product_id', 'NOT IN', $seckill_product_ids);
            $list = $model-> column('product_name');
        }


        return $this->renderSuccess('', compact('list'));

    }

    /**
     * 按分类输出商品列表
     */
    public function indexcategorylists()
    {
        // 整理请求的参数
        $param = array_merge($this->postData(), [
            'product_status' => 10,
            'audit_status' => 10,
            'is_show' => 1,    //显示可搜索
        ]);
        // 获取列表数据
        $model = new ProductModel;
        $list = $model->getList($param, $this->getUser(false));
        return $this->renderSuccess('', compact('list'));
    }

    /**
     * 非新人专属商品列表
     * @return \think\response\Json
     * @throws \app\common\exception\BaseException
     * @Author joey
     * @date 2024/2/24 14:06
     */
    public function olderProductlists()
    {
        // 整理请求的参数
        $param = array_merge($this->postData(), [
            'product_status' => 10,
            'audit_status' => 10,
            'is_show' => 1,    //显示可搜索
        ]);

        // 获取列表数据
        $model = new ProductModel;
        $list = $model->getProductListByType($param, $this->getUser(false), 0);
        return $this->renderSuccess('', compact('list'));
    }

    /**
     * 新人专属商品列表
     * @author joey
     * @date 2024/02/24
     * @return \think\response\Json
     * @throws \app\common\exception\BaseException
     */
    public function newcomerProductLists()
    {
        // 整理请求的参数
        $param = array_merge($this->postData(), [
            'product_status' => 10,
            'audit_status' => 10,
            'is_show' => 1,    //显示可搜索
        ]);

        // 获取列表数据
        $model = new ProductModel;
        $list = $model->getProductListByType($param, $this->getUser(false));
        return $this->renderSuccess('', compact('list'));
    }

    /**
     * 推荐产品
     */
    public function recommendProduct($location)
    {
        $recommend = SettingModel::getItem('recommend');
        $model = new ProductModel;
        $is_recommend = RecommendService::checkRecommend($recommend, $location);
        $list = [];
        if ($is_recommend) {
            $list = $model->getRecommendProduct($recommend);
        }
        return $this->renderSuccess('', compact('list', 'recommend', 'is_recommend'));
    }

    /**
     * 获取商品详情
     */
    public function detail($product_id, $url = '')
    {
        $params = $this->postData();
        // 用户信息
        $user = $this->getUser(false);
        // 商品详情
        $model = new ProductModel;
        $product = $model->getDetails($product_id, $this->getUser(false));
        if ($product === false || $product['audit_status'] != 10 || $product['product_status']['value'] != 10) {
            return $this->renderError($model->getError() ?: '商品信息不存在', [], 29);
        }
        // 多规格商品sku信息
        $specData = $product['spec_type'] == 20 ? $model->getManySpecData($product['spec_rel'], $product['sku']) : null;
        $isfollow = 0;
        if ($user) {
            if (FavoriteModel::detail($product_id, 20, $user['user_id'])) {
                $isfollow = 1;
            }
        }
        $product['isfollow'] = $isfollow;
        $dataCoupon['shop_supplier_id'] = $product['shop_supplier_id'];
        $model = new CouponModel;
        $couponList = $model->getWaitList($dataCoupon, $this->getUser(false), 1);
        // 访问记录
        (new VisitModel())->addVisit($user, $product['supplier'], $params['visitcode'], $product);
        // 优惠信息
        $discount = [
            // 商品满减
            'product_reduce' => FullReduceModel::getListByProduct($product_id),
            // 赠送积分
            'give_points' => $this->getGivePoints($product),
            // 商品优惠券
            'product_coupon' => $this->getCouponList($product),
        ];
        //是否显示优惠
        $show_discount = false;
        if (count($discount['product_reduce']) > 0
            || $discount['give_points'] > 0
            || count($discount['product_coupon']) > 0) {
            $show_discount = true;
        }

        $addPrices = 0;
        $newrs = StallProductModel::checkDB($params['stall_id']??0, $product['product_id']);
        if (isset($newrs['product_price'])&&$newrs['product_price']>0) {
            $addPrices = $newrs['product_price'];
            $product['product_price'] = bcadd($product['product_price'], $addPrices, 2);
        }
        //划线价规定
        // if($detail['product']['line_price']==0){
        // dump(json_encode($product['sku']));exit;
            if(isset($product['sku'])){
                $temp_line_price = $product['line_price'];
                foreach ($product['sku'] as $skey => $sval) {
                    if($sval['line_price']>$temp_line_price){
                        $temp_line_price = $sval['line_price'];
                        $product['line_price'] = $sval['line_price'];
                    }
                    $product['sku'][$skey]['product_price'] = bcadd($sval['product_price'], $addPrices, 2);
                }
            }
        if(isset($product['product_multi_spec'])){
            $atlist = $product['product_multi_spec']['spec_attr']??[];
            $clist = $product['product_multi_spec']['spec_list']??[];
            foreach ($clist as $bkey => $bval) {
                $baddval = $bval['spec_form']['product_price'];
                $clist[$bkey]['spec_form']['product_price'] = bcadd($baddval, $addPrices, 2);
            }
            $accc = [];
            $accc['spec_attr'] = $atlist;
            $accc['spec_list'] = $clist;
            $product['product_multi_spec'] = $accc;
        }
        // }
        return $this->renderSuccess('', [
            // 商品详情
            'detail' => $product,
            // 优惠信息
            'discount' => $discount,
            // 显示优惠
            'show_discount' => $show_discount,
            // 购物车商品总数量
            'cart_total_num' => $user ? (new CartModel())->getProductNum($user) : 0,
            // 多规格商品sku信息
            'specData' => $specData,
            // 微信公众号分享参数
            'share' => $this->getShareParams($url, $product['product_name'], $product['product_name'], '/pages/product/detail/detail', $product['image'][0]['file_path']),
            'couponList' => $couponList,
            //是否显示店铺信息
            'store_open' => SettingModel::getStoreOpen(),
            //是否开启客服
            'service_open' => SettingModel::getSysConfig()['service_open'],
            //店铺客服信息
            'mp_service' => ServiceModel::detail($product['shop_supplier_id']),
        ]);
    }

    /**
     * 赠送积分
     */
    private function getGivePoints($product)
    {
        if ($product['is_points_gift'] == 0) {
            return 0;
        }
        // 积分设置
        $setting = SettingModel::getItem('points');
        // 条件：后台开启开启购物送积分
        if (!$setting['is_shopping_gift']) {
            return 0;
        }
        // 积分赠送比例
        $ratio = $setting['gift_ratio'] / 100;
        // 计算赠送积分数量
        return helper::bcmul($product['product_price'], $ratio, 0);
    }

    /**
     * 获取商品可用优惠券
     */
    private function getCouponList($product)
    {
        // 可领取优惠券
        $model = new CouponModel;
        $user = $this->getUser(false);
        $couponList = $model->getList($user, null, true, $product['shop_supplier_id']);
        $coupon = [];
        foreach ($couponList as $key => $item) {
            if ($item['apply_range'] == 10) {
                $coupon[] = $item;
                // 限制商品
            } else if ($item['apply_range'] == 20) {
                $product_ids = explode(',', $item['product_ids']);
                if (in_array($product['product_id'], $product_ids)) {
                    $coupon[] = $item;
                }
                // 限制分类
            } else if ($item['apply_range'] == 30) {
                $category_ids = helper::getArrayColumn($item["category_list"], "category_id");
                if (in_array($product['category_id'], $category_ids)) {
                    $coupon[] = $item;
                }
            }
        }
        return $coupon;
    }

    /**
     * 预告产品
     */
    public function previewProduct()
    {
        // 整理请求的参数
        $param = array_merge($this->postData(), [
            'type' => 'preview',
            'is_show' => 1,    //显示可搜索
        ]);
        // 获取列表数据
        $model = new ProductModel;
        $list = $model->getList($param, $this->getUser(false));
        return $this->renderSuccess('', compact('list'));
    }

    /**
     * 生成商品海报
     */
    public function poster($product_id, $source)
    {
        // 商品详情
        $detail = ProductModel::detail($product_id);
        $Qrcode = new ProductService($detail, $this->getUser(false), $source);
        return $this->renderSuccess('', [
            'qrcode' => $Qrcode->getImage(),
        ]);
    }

    /**
     * 根据商品查询商家经营状态
     * @param $product_id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @Author joey
     * @date 2024/4/8 9:35
     */
    public function checkBusinessStatus($product_id)
    {
        // 商品详情
        $detail = ProductModel::with(['supplier'])->find($product_id);
        $result = $detail['supplier'];
        return $this->renderSuccess('', compact('result'));
    }
}
